package com.latex_demo;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;

import androidx.appcompat.widget.AppCompatTextView;

import org.scilab.forge.jlatexmath.core.AjLatexMath;
import org.scilab.forge.jlatexmath.core.Insets;
import org.scilab.forge.jlatexmath.core.TeXConstants;
import org.scilab.forge.jlatexmath.core.TeXFormula;
import org.scilab.forge.jlatexmath.core.TeXIcon;


public class LatexView extends AppCompatTextView {
    static final int MAX_IMAGE_WIDTH = (int) (Resources.getSystem().getDisplayMetrics().widthPixels * 0.8);

    public LatexView(Context context) {
        super(context);
    }

    public void setMath(String math) {
        setText(math);
//        try {
//            TeXFormula teXFormula = new TeXFormula(math);
//            Bitmap bitmap = getBitmap(teXFormula);
//            if (bitmap.getWidth() > MAX_IMAGE_WIDTH) {
//                bitmap = Bitmap.createScaledBitmap(bitmap, MAX_IMAGE_WIDTH,
//                        bitmap.getHeight() * MAX_IMAGE_WIDTH / bitmap.getWidth(),
//                        false);
//
//
//            }
//        } catch (Exception e) {
//            Logger.e("exception", e.getMessage());
//        }
        requestLayout();
    }

    private Bitmap getBitmap(TeXFormula formula) {
        TeXIcon icon = formula.new TeXIconBuilder()
                .setStyle(TeXConstants.STYLE_DISPLAY)
                .setSize(getPaint().getTextSize() / getPaint().density)
                .setWidth(TeXConstants.UNIT_SP, getPaint().getTextSize() / getPaint().density, TeXConstants.ALIGN_LEFT)
                .setIsMaxWidth(true)
                .setInterLineSpacing(TeXConstants.UNIT_SP,
                        AjLatexMath.getLeading(getPaint().getTextSize() / getPaint().density))
                .build();
        icon.setInsets(new Insets(5, 5, 5, 5));

        Bitmap image = Bitmap.createBitmap(icon.getIconWidth(), icon.getIconHeight(),
                Bitmap.Config.ARGB_4444);

        Canvas g2 = new Canvas(image);
        g2.drawColor(Color.TRANSPARENT);
        icon.paintIcon(g2, 0, 0);
        return image;
    }
}
